package main;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.regex.*;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpringLayout;

/**
 * Dialog box to add a new contact.
 * 
 * @author Olga
 */
public class NewContactWindow extends JDialog {
    
    private static final String PAGETITLE = "Add a Contact";

    private JPanel mainPanel;
    private JPanel infoPanel;
    private JPanel notesPanel;
    private JPanel buttonPanel;
    private JButton addButton;
    private JButton cancelButton;

    private JLabel firstNameLabel;
    private JLabel lastNameLabel;
    private JLabel emailLabel;
    private JLabel phoneLabel;
    private JLabel addressLabel;
    private JLabel zipLabel;
    private JLabel notesLabel;

    private JTextField firstNameTextField;
    private JTextField lastNameTextField;
    private JTextField emailTextField;
    private JTextField phoneTextField;
    private JTextField addressTextField;
    private JTextField zipTextField;
    private JTextArea notesTextField;

    /**
     * Constructor for the dialog box. Adds the labels, text fields, and buttons
     * as well as the action listeners for the buttons. Sets size and sets
     * formatting
     * 
     * @param controller
     *            the gui event handler
     * 
     */
    public NewContactWindow(ActionListener controller) {

        this.setIconImage(Toolkit.getDefaultToolkit().getImage("res/icon.png"));
        
        mainPanel = new JPanel();
        infoPanel = new JPanel();
        notesPanel = new JPanel();
        buttonPanel = new JPanel();
        
        firstNameLabel = new JLabel("First Name:", JLabel.TRAILING);
        lastNameLabel = new JLabel("Last Name:", JLabel.TRAILING);
        emailLabel = new JLabel("Email:", JLabel.TRAILING);
        phoneLabel = new JLabel("Phone Number:", JLabel.TRAILING);
        addressLabel = new JLabel("Street Address:", JLabel.TRAILING);
        zipLabel = new JLabel("Zip Code:", JLabel.TRAILING);
        notesLabel = new JLabel("Additional Notes:", JLabel.TRAILING);

        firstNameTextField = new JTextField(15);
        lastNameTextField = new JTextField(15);
        emailTextField = new JTextField(15);
        phoneTextField = new JTextField(15);
        addressTextField = new JTextField(15);
        zipTextField = new JTextField(15);
        notesTextField = new JTextArea(3,40);

        addButton = new JButton("Add");
        addButton.addActionListener(controller);
        addButton.setActionCommand("new_add");
        cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(controller);
        cancelButton.setActionCommand("new_cancel");
        
        infoPanel.setLayout(new SpringLayout());

        infoPanel.add(firstNameLabel);
        infoPanel.add(firstNameTextField);

        infoPanel.add(lastNameLabel);
        infoPanel.add(lastNameTextField);

        infoPanel.add(emailLabel);
        infoPanel.add(emailTextField);

        infoPanel.add(phoneLabel);
        infoPanel.add(phoneTextField);

        infoPanel.add(addressLabel);
        infoPanel.add(addressTextField);

        infoPanel.add(zipLabel);
        infoPanel.add(zipTextField);
        
        SpringUtilities.makeCompactGrid(infoPanel,
                3,4,
                6,6,
                6,6);

        notesPanel.add(notesLabel);
        notesPanel.add(notesTextField);
        
        buttonPanel.add(addButton);
        buttonPanel.add(cancelButton);
        
        mainPanel.add(infoPanel);
        mainPanel.add(notesPanel);
        mainPanel.add(buttonPanel);
        
        this.getRootPane().setDefaultButton(addButton);
        
        this.add(mainPanel);
        this.setTitle(Main.TITLE + ": " + PAGETITLE);

        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        pack();
        setResizable(false);
    }

    /**
     * Opens an error dialog box should an error happen
     * 
     * @return Either the contact or null if an error was reached
     */
    public Contact getContact() {

        boolean noError = true;

        String firstName = firstNameTextField.getText();
        String lastName = lastNameTextField.getText();
        String emailAddress = emailTextField.getText();
        String phoneNumber = phoneTextField.getText();
        String streetAddress = addressTextField.getText();
        String zipCode = zipTextField.getText();
        String notes = notesTextField.getText();

        // Check to see if first name is present
        if (firstNameTextField.getText() != null
                && firstNameTextField.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "No First Name.", "Error.",
                    JOptionPane.ERROR_MESSAGE);
            noError = false;
        }

        // Check to see if last name is present
        if (lastNameTextField.getText() != null
                && lastNameTextField.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "No Last Name.", "Error.",
                    JOptionPane.ERROR_MESSAGE);
            noError = false;
        }

        // Uses validateEmail and prints error message
        if (!validateEmail(emailAddress)) {
            JOptionPane.showMessageDialog(null, "Invalid Email.", "Error.",
                    JOptionPane.ERROR_MESSAGE);
            noError = false;
        }

        // Check to see if Phone Number is valid
        if (phoneNumber.length() != 10) {
            JOptionPane.showMessageDialog(null, "Invalid Phone Number.",
                    "Error.", JOptionPane.ERROR_MESSAGE);
            noError = false;
        }

        if (noError) {
            return new Contact(firstName, lastName, streetAddress, zipCode,
                    emailAddress, phoneNumber, notes);
        } else {
            return null;
        }
    }

    /**
     * Checks email validity
     * 
     * @param email
     *            the email string in question
     * @return true if email is valid, false if email is invalid
     */
    public static boolean validateEmail(String email) {
        String emailToVaidate = "checkmy@gmail.com";
        String regEx = "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b";

        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(email);

        boolean result = false;
        if (m.find()) {
            result = true;
        }

        return result;
    }

}
